﻿using System;
using System.Linq;
using System.Web.Mvc;

using mvcForum.Core;
using mvcForum.Web.Controllers;
using mvcForum.Web.Extensions;
using CategoryVM = mvcForum.Web.Areas.ForumAPI.ViewModels.Category;
using ForumLight = mvcForum.Web.Areas.ForumAPI.ViewModels.ForumLight;
using mvcForum.Core.Interfaces.Data;

namespace mvcForum.Web.Areas.ForumAPI.Controllers {

	public class CategoryController : BaseAPIController {

		[HttpPost]
		[Authorize(Roles = Constants.Roles.Combined)]
		public ActionResult Create(CategoryVM model, String mode) {
			if (ModelState.IsValid) {
				Board board = this.GetRepository<Board>().Read(model.BoardId);
				// TODO: Access!

				Category category = new Category(board, model.Name, model.SortOrder);

				this.GetRepository<Category>().Create(category);

				this.Context.SaveChanges();

				return new HttpStatusCodeResult(200);
			}

			return new HttpStatusCodeResult(500, ModelState.ErrorString());
		}

		public ActionResult Read(Int32 id, String mode) {
			// TODO: Access!
			Category category = this.GetRepository<Category>().Read(id);
			return this.CustomJson(new CategoryVM {
				Id = category.Id,
				BoardId = category.Board.Id,
				BoardUrl = Url.Action("read", "board", new { area = "forumapi", id = category.Board.Id, mode = "json" }),
				SortOrder = category.SortOrder,
				Name = category.Name
			});
		}

		[HttpPost]
		[Authorize(Roles = Constants.Roles.Combined)]
		public ActionResult Update(CategoryVM model, String mode) {
			if (ModelState.IsValid) {
				Category category = this.GetRepository<Category>().Read(model.Id);
				// TODO: Access!!!
				category.Name = model.Name;
				category.SortOrder = model.SortOrder;

				this.Context.SaveChanges();

				return new HttpStatusCodeResult(200);
			}

			return new HttpStatusCodeResult(500, ModelState.ErrorString());
		}

		[HttpPost]
		[Authorize(Roles = Constants.Roles.Combined)]
		public ActionResult Delete(Int32 id, String mode) {
			IRepository<Category> catRepo = this.GetRepository<Category>();

			Category category = catRepo.Read(id);
			// TODO: Delete categories, forums, topics, etc. etc.
			catRepo.Delete(category);

			this.Context.SaveChanges();

			return new HttpStatusCodeResult(200);
		}

		/// <summary>
		/// Lists the forums below the category with the given Id.
		/// </summary>
		/// <param name="id"></param>
		/// <param name="mode"></param>
		/// <returns></returns>
		public ActionResult List(Int32 id, String mode) {
			// TODO: Access!
			Category category = this.GetRepository<Category>().Read(id);
			return this.CustomJson(new {
				Forums = category.Forums.Where(f => f.ParentForum == null).Select(f => new ForumLight {
					Id = f.Id,
					Name = f.Name,
					SortOrder = f.SortOrder,
					ApiUrl = Url.Action("read", "forum", new { area = "forumapi", mode = "json", id = f.Id })
				}).OrderBy(f => f.SortOrder)
			});
		}
	}
}